package com.gopay.scheduler.job;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.gopay.common.constants.mail.MailLevel;
import com.gopay.common.domain.cert.CorpMsgSignCert;
import com.gopay.common.domain.mail.Send;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.user.UserSmsRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.mail.MailEngine;
import com.gopay.scheduler.service.cacert.CorpMsgSignCertService;
import com.gopay.sms.client.GopaySMSHttpClient;
import com.gopay.sms.common.constants.SMSAppId;
import com.gopay.sms.common.domain.RequestVO;
import com.gopay.sms.common.domain.ResponseVO;

import net.sf.json.JSONObject;

/**
 * 服务器数字证书过期邮件提醒任务
 * 
 * @CorpMsgSignCertNotifyJob.java
 * @author zhuliang
 * @2016年9月27日 下午4:15:44 www.gopay.com.cn Inc.All rights reserved.
 */
public class CorpMsgSignCertNotifyJob extends GopayBaseJob {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
    private @Value("#{webProperties['portal.url']}")
    String portalUrl; // 此处暂时使用portalUrl
	@Resource(name = "corpMsgSignCertService")
	private CorpMsgSignCertService serverCertService;
	@Resource(name = "userSmsRemoteClient")
	private UserSmsRemoteService userSmsRemoteClient;
    @Resource(name = "mailEngine")
    private MailEngine mailEngine;

    //邮箱正则表达式
    private Pattern p = Pattern.compile("^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$");
    
	@Override
	protected void doJobInternal() {
		logger.error("CorpMsgSignCertNotifyJob------------start---------");
		logger.error("开始处理服务器数字证书过期邮件提醒任务");
		/**
		 * 提前3个月通过邮箱进行提醒，每周一上午十点，连续发送12周，直至证书过期后不再提醒
		 */
		List<CorpMsgSignCert> custList = serverCertService.getCorpMsgSignCertList();
        if (custList != null && custList.size() > 0) {
            logger.error("查询获取到的过期服务器签名证书的数量为： " + custList.size());
            int successCount = 0;
            for (CorpMsgSignCert corpMsgSignCert : custList) {
                try {

                    String custEmail = corpMsgSignCert.getCertEmail();
                    Matcher m = p.matcher(custEmail);
                    if(m.matches()){
                        // 企业管理员用户 发邮件
                        logger.error("企业发送邮箱为: " + corpMsgSignCert.getCertEmail() + ",custId: " + corpMsgSignCert.getCustId());
                        sendMail(corpMsgSignCert.getCertEmail(), corpMsgSignCert.getCertAlias(),corpMsgSignCert.getValidTo());
                    }else {
                        logger.error("企业发送手机为: " + corpMsgSignCert.getCertEmail() + ",custId: " + corpMsgSignCert.getCustId());
                        sendSms(corpMsgSignCert.getCertEmail(), corpMsgSignCert.getValidTo());
                    }
                    
                    successCount++;
                    logger.info("第" + successCount + "条通知成功,Id: " + corpMsgSignCert.getId());

                } catch (GopayException e) {
                    logger.error("通知服务器数字证书失败,certCustId:" + corpMsgSignCert.getCustId());
                    logger.error(e.getMessage());
                } catch (Exception e) {
                    logger.error("通知服务器数字证书失败,certCustId:" + corpMsgSignCert.getCustId());
                    logger.error(e.getMessage());
                }
            }
            logger.error("修改成功数： " + successCount);
            logger.error("处理服务器数字证书过期提醒结束。");
        } else {
            logger.info("服务器数字证书未找到需要提醒的数据列表.");
        }

	}

	/**
	 * 发送短信
	 * @param mobile
	 * @param limitDate
	 * @throws GopayException 
	 */
	private void sendSms(String mobile, Date limitDate) throws GopayException {
		String remidDdate = DateUtils.format(limitDate, "yyyy-MM-dd");
		
		RequestVO req = new RequestVO();
		req.setAppId(SMSAppId._90001.value);
		req.setMobile(mobile);
		req.setContent("您的服务器签名证书将于" + remidDdate + "到期，"
						+ "为确保您的交易安全，请在到期日前登录国付宝账户进行更新，证书过期后将阻断交易。 ");
		ResponseVO resp = GopaySMSHttpClient.getInstance()
				.createVerificationCode(req);

		if (resp != null) {
			if ("100".equals(resp.getStatusCode())) {
				logger.error("短信提醒数字证书过期，已经发送成功！");
			} else {
				logger.error("短信提醒数字证书过期，发送失败！，原因：" + resp.getMessage());
				throw new GopayException("短信提醒数字证书过期，发送失败！，原因：" + resp.getMessage());
			}
		}
	}
	private void sendMail(String Email,String custName,Date limitDate) throws GopayException{
		  String email = Email.trim().toLowerCase();
		  String remidDdate = DateUtils.format(limitDate, "yyyy-MM-dd");
          Send send = new Send();
          send.setReceivers(email);// 收件人
          send.setTemplate("custSignCertRemind");
          send.setLevel(MailLevel.MID);
          Map<String, Object> json = new HashMap<String, Object>();
          json.put("replacethistotheUSERNAME", custName);
          json.put("replacethistotheLogoAddr", portalUrl);
          json.put("replacethistotheLimitDate", remidDdate);
          send.setContent(JSONObject.fromObject(json).toString());
          serverCertService.sendMail(send);
	}

	/**
	 * @return the portalUrl
	 */
	public String getPortalUrl() {
		return portalUrl;
	}

	/**
	 * @param portalUrl the portalUrl to set
	 */
	public void setPortalUrl(String portalUrl) {
		this.portalUrl = portalUrl;
	}
    
}

